/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.mqtt.server.controller;

import com.alibaba.fastjson2.JSON;
import com.google.protobuf.Message;
import info.peigen.hotpot.component.gateway.mqtt.server.controller.form.MqttServerControllerForm;
import info.peigen.hotpot.component.gateway.mqtt.server.service.MqttServerPublishService;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <b>(MqttServerSampleController)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/7/19
 */
@Slf4j
@Controller
@Mapping("/mqtt/server")
public class MqttServerController {
    @Inject
    private MqttServerPublishService mqttServerPublishService;

    /**
     * @param form form
     *
     * @return boolean
     */
    @Mapping("/publish")
    public boolean publish(@Body MqttServerControllerForm form) {
        log.info("收到publish请求:form={}", JSON.toJSON(form));
        return mqttServerPublishService.publish(form.getClientId(), form.getTopic(), form.getBody());
    }

    /**
     * @param form form
     *
     * @return boolean
     */
    @Mapping("/publishAll")
    public boolean publishAll(@Body MqttServerControllerForm form) {
        log.info("收到publishAll请求:form={}", JSON.toJSON(form));
        Class  clz    = null;
        Method method = null;
        Object obj    = null;
        try {
            clz = Class.forName(form.getMessageClass());
            method = clz.getMethod("newBuilder");
            obj = method.invoke(null);
        } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        Message.Builder builder = (Message.Builder) obj;
        return mqttServerPublishService.publishAllByJson(form.getTopic(), form.getBody(), builder);
    }
}